import { _decorator, Component, Node, BaseNode, Animation, director, Prefab, instantiate, Label, Sprite, resources, ImageAsset, SpriteFrame, Button, Script } from 'cc';
import Levels from './Levels';
import { Main } from './Main';
const { ccclass, property } = _decorator;

@ccclass('Index')
export class Index extends Component {
    static Show: boolean = false;
    @property(Node)
    Header: BaseNode;
    @property(Node)
    Main: BaseNode;
    @property(Prefab)
    Level: Prefab;
    @property(Node)
    Body: BaseNode;
    start() {
        this.init();
    }
    init() {
        Levels.forEach(item => {
            const node = instantiate(this.Level);
            node.getComponent(Button).clickEvents[0].target = this.node;
            node.getComponent(Button).clickEvents[0].component = 'Index';
            node.getComponent(Button).clickEvents[0].handler = 'onclick';
            resources.load(item.level, ImageAsset, (err, ImgData) => {
                if (!err) {
                    const Img = SpriteFrame.createWithImage(ImgData);
                    node.children[0].getComponent(Sprite).spriteFrame = Img;
                }
            });
            node.children[1].getComponent(Label).string = item.title;
            this.Body.addChild(node);
        });
    }
    update() {
        switch (Index.Show) {
            case true:
                this.Header.active = false;
                this.Main.active = true;
                break;
            case false:
                this.Header.active = true;
                this.Main.active = false;
                break;
        }
    }
    onclick({ target }) {
        const node: Node = target;
        node.getComponent(Animation).play();
        setTimeout(() => {
            switch (node.name) {
                case 'Start':
                    director.loadScene('Main')
                    break;
                case 'Levels':
                    Index.Show = true;
                    break;
                case 'Break':
                    Index.Show = false;
                default:
                    if (RegExp(/^(Level)/, 'g').test(node.name)) {
                        Main.level = Levels[this.Body.children.indexOf(node)];
                        director.loadScene('Main');
                    }
            }
        }, 500);
    }
    onDestroy() {
        Index.Show = false;
    }
}


